package com.zcc.blog.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcc.blog.dto.LoginDto;
import com.zcc.blog.entity.User;
import com.zcc.blog.service.AccountService;
import com.zcc.blog.service.UserService;
import com.zcc.blog.untils.JwtUtils;
import com.zcc.blog.untils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.format.DateTimeFormatter;

/**
 * @author xiaomi
 */
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    UserService userService;
    @Autowired
    JwtUtils jwtUtils;

    @Override
    public Result login(LoginDto loginDto, HttpServletResponse response) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        System.out.println("用户"+user);
        // 判断用户是否存在
        if (user == null) {
            return Result.fail("用户不存在");
        } else {
            // 判断账号密码是否错误(md5加密判断)
            if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
                return Result.fail("密码不正确");
            }
            String jwt = jwtUtils.generateToken(user.getId());
            userService.updateLastLogin(user.getId());
            //设置header
            response.setHeader("Authorization",jwt);
            response.setHeader("Access-control-Expose-Headers","Authorization");

            return Result.success(MapUtil.builder()
                    .put("id",user.getId())
                    .put("username",user.getUsername())
                    .put("avatar",user.getAvatar())
                    .put("email",user.getEmail())
                    .put("created", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(user.getCreated()))
                    .put("lastLogin", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(user.getLastLogin())).map()
            );
        }
    }

    @Override
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()) {
            subject.logout();
        }
        return Result.success("退出登录");
    }
}
